package com.ita.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

public class DBUtil {

	private static String DRIVER_NAME = "oracle.jdbc.OracleDriver";
	private static String URL = "jdbc:oracle:thin:@zha-ita105-w7:1521:orcl";
	private static String USER_NAME = "bryce";
	private static String PASSWORD = "123";
	private static DataSource jndiDs;

	static {
		try {
			Context cxt = new InitialContext();
			jndiDs = (DataSource) cxt.lookup("java:/comp/env/jdbc/myoracle");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static Connection createConnection() {

		Connection conn = null;
		try {
			Class.forName(DRIVER_NAME);
			conn = DriverManager.getConnection(URL, USER_NAME, PASSWORD);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}

	public static Connection createByJNDI() {

		Connection conn = null;
		try {
			return jndiDs.getConnection();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}

	public static void close(Connection conn, PreparedStatement pst,
			ResultSet rSet) {

		try {
			if (conn != null) {
				conn.close();
			}
			if (pst != null) {
				pst.close();
			}
			if (rSet != null) {
				rSet.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
